#include "FileDialog.h"
#include <boost/regex.hpp>
using namespace boost::filesystem;

FileDialog::FileDialog()
    : fileColour(1,1,1), directoryColour(0,0,1), selectionColour(0,0,0), listWindowName("FileList"), fileFilter(".*")
{
    overseerPath = getCurrentPath();
}

FileDialog::~FileDialog()
{
    current_path(overseerPath);
}


void FileDialog::setListWindowName(std::string n)
{
    listWindowName = n;
}

std::string FileDialog::getCurrentPath()
{
    return current_path().string();
}

std::string FileDialog::getFullPathName(std::string filename)
{
    return absolute(path(filename)).string();
}

void FileDialog::setFileFilter(std::string regex)
{
    fileFilter = regex;
}

int FileDialog::openPath(std::string pathName)
{
    CEGUI::Listbox *fileList = (CEGUI::Listbox*)CEGUI::WindowManager::getSingletonPtr()->getWindow(listWindowName);
    path p(pathName);

    boost::regex fileRegex(fileFilter);
    boost::smatch what;

    if (!exists(p)) return 2;
    if (!is_directory(p) && boost::regex_match(p.filename().generic_string(),what,fileRegex)) return 1;

    fileList->resetList();

    CEGUI::uint item_id=0;

    std::vector<path> files;
    copy(directory_iterator(p),directory_iterator(),back_inserter(files));
    sort(files.begin(),files.end(),sortPaths);
    files.insert(files.begin(),path(".."));
    for(std::vector<path>::iterator it = files.begin(); it != files.end(); it++)
    {
        if (!is_directory(*it) && !boost::regex_match(it->filename().generic_string(),what,fileRegex)) continue;
        CEGUI::ListboxTextItem *listItem = new CEGUI::ListboxTextItem(it->filename().generic_string(),item_id++);
        if (is_directory(*it)) listItem->setTextColours(directoryColour);
        else listItem->setTextColours(fileColour);
        listItem->setSelectionColours(selectionColour);
        listItem->setSelectionBrushImage("TaharezLook","MultiListSelectionBrush");
        fileList->addItem(listItem);
    }
    current_path(p);
    return 0;
}

void FileDialog::setSelectionColour(float r, float g, float b)
{
    selectionColour = CEGUI::colour(r,g,b);
}

void FileDialog::setDirectoryColour(float r, float g, float b)
{
    directoryColour = CEGUI::colour(r,g,b);
}

void FileDialog::setFileColour(float r, float g, float b)
{
    fileColour = CEGUI::colour(r,g,b);
}

bool sortPaths(path a, path b)
{
    bool a_is_directory = is_directory(a), b_is_directory = is_directory(b);
    if (!(a_is_directory ^ b_is_directory)) return a < b;
    else return a_is_directory;
}
